package translate;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;

public class Translate {

	private static Translate instance;

	private ArrayList<String> strings;
	private ArrayList<String> translated;

	private final static String FILEPATH = "translation.txt";

	private Translate(){
		strings = new ArrayList<String>();
		translated = new ArrayList<String>();

		loadTranslations();
	}

	private void loadTranslations(){
		Path file = Paths.get(FILEPATH);
		Scanner scanner;

		try {
			scanner = new Scanner(file);
			while (scanner.hasNextLine()){
				String line = scanner.nextLine();
				if(line.length() > 0){
					int splitIndex = line.indexOf(";");

					strings.add(line.substring(0, splitIndex));
					translated.add(line.substring(splitIndex+1));
				}
			}
			scanner.close();
		} catch (IOException e) {
			System.out.println("No translation file");
		}
	}

	private static void init() {
		if(instance == null)
			instance = new Translate();
	}

	public static String print(String string) {
		init();
		
		int stringIndex = instance.isString(string);

		if(stringIndex > -1){
			if(stringIndex < instance.translated.size()){
				String tempTranslated = instance.translated.get(stringIndex);
				if(tempTranslated.length() > 0)
					return tempTranslated;
			}
		}
		else
			instance.addString(string);

		return string;
	}
	
	public static String print(String string, Object...args) {

		return String.format(print(string), args);
	}

	private void addString(String string){
		instance.strings.add(string);
		instance.translated.add("");

		// http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
		// http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java

		try {
			FileWriter fw = new FileWriter(FILEPATH, true);
			System.out.println(fw.getEncoding());
			fw.write("\n" + string + ";");
			fw.close();
		} catch (IOException e) {
			System.out.println("NO FILE");
		}
		//	BufferedWriter bw = new BufferedWriter(fw);
		//	bw.write(content);
		//	bw.close();

	}

	private int isString(String search){
		for (int i = 0; i < instance.strings.size(); i++) {
			if(instance.strings.get(i).equals(search))
				return i;
		}
		return -1;
	}

	@Override
	public String toString() {
		return instance.strings.toString() + instance.translated.toString();
	}

}
